<template>
  <div class="search">
    <div class="search-box">
      <div class="iconfont icon-search">&#xe62e;</div>
      <input type="text" placeholder="城市拼音或者名称" v-model="keyword">
    </div>
    <div class="search-content" v-show="keyword">
      <ul class="list">
        <li v-for="item in list" :key="item.id" @click="handleCityClick(item.name)">{{item.name}}</li>
        <li v-show="!showResult">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>
<script>
export default {
  name: "CitySearch",
  data() {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  props: {
    cities: Object
  },
  methods:{
    handleCityClick(city){
      this.keyword = ''
      this.$store.dispatch('changeCity', city)
      this.$router.go(-1)
    }
  },
  computed:{
    showResult() {
      return this.list.length
    }
  },
  watch: {
    keyword() {
      if(this.timer){
        clearTimeout(this.timer)
      }
      if(!this.keyword){
        this.list = []
        return 
      }
      this.timer = setTimeout(() => {
        let result = []
        for (let i in this.cities) {
          this.cities[i].forEach(item => {
            if (item.spell.indexOf(this.keyword) > -1 ||
            item.name.indexOf(this.keyword) > -1) {
              result.push(item)
            }
            this.list = result
          })
        }
      }, 100)
    }
  },
}
</script>
<style lang="scss" scoped>
  @import '../../../assets/base.scss';
  .search{
    padding: 10px 20px;
    height: 60px;
    background-color: $headerColor;
    .search-box{
      width: 100%;
      height: 100%;
      display: flex;
      background-color: #fff;
      border-radius: 5px;
      .icon-search{
        width: 60px;
        height: 100%;
        flex-shrink: 0;
        font-size: 45px;
        text-align: center;
        line-height: 60px;
        color: #ccc;
      }
      input{
        flex: 1;
        background-color: transparent;
        &::placeholder{
          color: #ccc;
        }
      }
    }
    .search-content{
      position: absolute;
      top: 160px;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 5;
      background-color: #f5f5f5;
      .list{
        background-color: #fff;
        li{
          margin: 0 20px;
          height: 60px;
          line-height: 60px;
          font-size: 28px;
          color: #666;
          border-bottom: 2px solid #f5f5f5;
        }
      }
    }
  }
  
</style>
